﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infrastructure;
using PickingBusiness;
using Picking.Common;
using System.IO;
using Infrastructure.Util;

namespace Picking_Winform
{
    public partial class WorkersAndLightsSetupView : FormBase
    {
        private int currentWorkerCount = 0;
        private int MaxLightAddress = ConfigInfo.MaxLightAddress1;
        private int MinLightAddress = ConfigInfo.MinLightAddress1;
        private WorkersAndLightsSetupModel model = new WorkersAndLightsSetupModel();

        /// <summary>
        /// Constructor
        /// </summary>
        public WorkersAndLightsSetupView()
        {
            InitializeComponent();
            this.Controls.Add(base.txtTitle);
            this.comboBox1.Items.Clear();
            this.comboBox1.Items.AddRange(base.items);
            this.comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// Get Form Width
        /// </summary>
        /// <returns></returns>
        protected override int GetFormWidth()
        {
            return 820;
        }

        /// <summary>
        /// Set Form Title
        /// </summary>
        private void SetFormTitle()
        {
            this.Text = txtTitle.Text = "配料人数和棚灯数设定";
        }

        /// <summary>
        /// Form Shown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WorkersAndLightsSetupView_Shown(object sender, EventArgs e)
        {
            this.SetFormTitle();
        }

        /// <summary>
        /// Form Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WorkersAndLightsSetupView_Load(object sender, EventArgs e)
        {
            this.GetWorkersAndLightsSetup();
            this.InitWorkersNumber();
        }

        private string GetLineCode()
        {
            string lineCode = ConfigInfo.LineCodeA;

            if (this.comboBox1.SelectedIndex == 0)
            {
                lineCode = ConfigInfo.LineCodeA;
            }
            else if (this.comboBox1.SelectedIndex == 1)
            {
                lineCode = ConfigInfo.LineCodeB;
            }
            else if (this.comboBox1.SelectedIndex == 2)
            {
                lineCode = ConfigInfo.LineCodeC;
            }

            return lineCode;
        }

        /// <summary>
        /// Get Current WorkersAndLightsSetup Data From Database
        /// </summary>
        private void GetWorkersAndLightsSetup()
        {
            string lineCode = this.GetLineCode();
            this.model = Configuration.GetWorkersAndLightsSetup(lineCode);

            this.currentWorkerCount = model.WorkersAndLightsSetupTable.Rows.Count;

            this.FormatLightNo(this.model.WorkersAndLightsSetupTable, true);

            this.grdWorkerAndLightSet.DataSource = model.WorkersAndLightsSetupTable;
        }

        /// <summary>
        /// Init Workers Number
        /// </summary>
        private void InitWorkersNumber()
        {
            if (this.currentWorkerCount <= 0)
            {
                this.txtWorkerCount.Text = ConfigInfo.MaxWorkerCount1.ToString();
            }
            else
            {
                this.txtWorkerCount.Text = this.currentWorkerCount.ToString();
            }

            this.lblWorkerStartNumber.Text = ConfigInfo.MinWorkerCount1.ToString();
            this.lblWorkerEndNumber.Text = ConfigInfo.MaxWorkerCount1.ToString();
        }

        /// <summary>
        /// Format Light No
        /// </summary>
        /// <param name="table"></param>
        /// <param name="isFormat"></param>
        private void FormatLightNo(DataTable table, bool isFormat)
        {
            if (isFormat)
            {
                foreach (DataRow row in table.Rows)
                {
                    row["Light_Start_No"]
                        = int.Parse(row["Light_Start_No"].ToString()).ToString("0000");

                    row["Light_End_No"]
                       = int.Parse(row["Light_End_No"].ToString()).ToString("0000");
                }
            }
            else
            {
                foreach (DataRow row in table.Rows)
                {
                    row["Light_Start_No"]
                        = int.Parse(row["Light_Start_No"].ToString());

                    row["Light_End_No"]
                       = int.Parse(row["Light_End_No"].ToString());
                }
            }

        }

        /// <summary>
        /// Do Validation
        /// </summary>
        /// <returns></returns>
        private bool DoValidation(bool isSave)
        {
            List<int> lightNumbers = new List<int>();

            foreach (DataRow row in this.model.WorkersAndLightsSetupTable.Rows)
            {
                int startLightNumber = 0;
                int endLightNumber = 0;

                string lightStartNo = row["Light_Start_No"].ToString().Trim();
                string lightEndNo = row["Light_End_No"].ToString().Trim();

                if (string.IsNullOrEmpty(lightStartNo))
                {
                    if (isSave)
                    {
                        MessageBox.Show("开始棚灯号不能为空!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                        return false;
                    }
                }
                else
                {
                    if (!int.TryParse(lightStartNo, out startLightNumber))
                    {
                        MessageBox.Show("开始棚灯号必须是个整型数值!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (startLightNumber > this.MaxLightAddress)
                    {
                        MessageBox.Show("开始棚灯号必须小于或等于最大棚灯号：" + this.MaxLightAddress.ToString() + "!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (startLightNumber < this.MinLightAddress)
                    {
                        MessageBox.Show("开始棚灯号必须大于或等于最小棚灯号：" + this.MinLightAddress.ToString() + "!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }
                }

                if (string.IsNullOrEmpty(lightEndNo))
                {
                    if (isSave)
                    {
                        MessageBox.Show("结束棚灯号不能为空!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                        return false;
                    }
                }
                else
                {
                    if (!int.TryParse(lightEndNo, out endLightNumber))
                    {
                        MessageBox.Show("结束棚灯号必须是个整型数值!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (endLightNumber > this.MaxLightAddress)
                    {
                        MessageBox.Show("结束棚灯号必须小于或等于最大棚灯号：" + this.MaxLightAddress.ToString() + "!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (endLightNumber < this.MinLightAddress)
                    {
                        MessageBox.Show("结束棚灯号必须大于或等于最小棚灯号：" + this.MinLightAddress.ToString() + "!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }
                }

                if (!string.IsNullOrEmpty(lightStartNo)
                    && !string.IsNullOrEmpty(lightEndNo))
                {
                    if (startLightNumber > endLightNumber)
                    {
                        MessageBox.Show("结束棚灯号必须大于或等于开始棚灯号!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    for (int i = startLightNumber; i <= endLightNumber; i++)
                    {
                        if (!lightNumbers.Contains(i))
                        {
                            lightNumbers.Add(i);
                        }
                        else
                        {
                            MessageBox.Show("不同配料人员的棚灯号范围不能交叉!",
                                            "验证",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                            return false;
                        }

                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Save Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            this.btnSave.Focus();

            this.grdWorkerAndLightSet.EndEdit();

            if (!this.DoValidation(true))
            {
                return;
            }

            this.model.WorkersAndLightsSetupTableCopy
                = this.model.WorkersAndLightsSetupTable.Copy();

            this.FormatLightNo(this.model.WorkersAndLightsSetupTableCopy, false);

            string lineCode = this.GetLineCode();
            bool result = Configuration.SaveWorkersAndLightsSetup(this.model, lineCode);

            if (result)
            {
                MessageBox.Show("保存成功!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
                SaveToIniFile(this.grdWorkerAndLightSet.DataSource as DataTable, System.Configuration.ConfigurationManager.AppSettings["IniFilePath"]);
            }
            else
            {
                MessageBox.Show("保存失败!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SaveToIniFile(DataTable dataTable, string fileName)
        {
            StringBuilder sbData = new StringBuilder();

            foreach (DataRow row in dataTable.Rows)
            {
                foreach (DataColumn column in dataTable.Columns)
                {
                    string cn = string.Empty;
                    switch (column.ColumnName)
                    {
                        case "Picking_Worker_No": cn = "人数设定"; break;
                        case "Light_Start_No": cn = "开始棚灯号"; break;
                        case "Light_End_No": cn = "结束棚灯号"; break;
                        default:
                            break;
                    }
                    if (column.ColumnName == "Light_Sign") continue;
                    sbData.Append(cn + ":" + row[column].ToString() + ";");
                }
                sbData.AppendLine();
            }
            sbData.AppendLine();

            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = System.Text.Encoding.GetEncoding(System.Configuration.ConfigurationManager.AppSettings["CSVEncoding"]).GetBytes(sbData.ToString());
                fs.Write(buffer, 0, buffer.Length);
            }
        }

        /// <summary>
        /// Cancel Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.txtWorkerCount.Text = string.Empty;
            this.btnCancel.Focus();
            this.GetWorkersAndLightsSetup();
            this.InitWorkersNumber();
        }

        /// <summary>
        /// Return Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.CloseCurrentWindow();
        }

        /// <summary>
        /// Worker Count Changed Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtWorkerCount_TextChanged(object sender, EventArgs e)
        {
            int newWorkerCount = 0;
            int countTemp = 0;

            int currentWorkerCount
                    = this.model.WorkersAndLightsSetupTable.Rows.Count;

            if (int.TryParse(this.txtWorkerCount.Text.Trim(), out countTemp))
            {
                newWorkerCount = countTemp;

                if ((newWorkerCount <= ConfigInfo.MaxWorkerCount1)
                    && (newWorkerCount >= ConfigInfo.MinWorkerCount1))
                {
                    if (currentWorkerCount > newWorkerCount)
                    {
                        for (int i = currentWorkerCount - 1; i >= newWorkerCount; i--)
                        {
                            this.model.WorkersAndLightsSetupTable.Rows.RemoveAt(i);
                        }
                    }
                    else if (currentWorkerCount < newWorkerCount)
                    {
                        for (int i = currentWorkerCount + 1; i <= newWorkerCount; i++)
                        {
                            this.model.WorkersAndLightsSetupTable.Rows.Add(i, "", "~", "");
                        }
                    }

                    this.grdWorkerAndLightSet.DataSource = model.WorkersAndLightsSetupTable;
                }
                else
                {
                    this.txtWorkerCount.Text = currentWorkerCount.ToString();
                }
            }
            else if (!string.IsNullOrEmpty(this.txtWorkerCount.Text.Trim()))
            {
                this.txtWorkerCount.Text = currentWorkerCount.ToString();
            }
        }

        /// <summary>
        /// Cell End Edit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdWorkerAndLightSet_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (this.btnCancel.Focused)
            {
                return;
            }

            int temp = 0;
            string cellValue = this.grdWorkerAndLightSet[e.ColumnIndex, e.RowIndex].Value.ToString();
            if (int.TryParse(cellValue, out temp))
            {
                this.grdWorkerAndLightSet[e.ColumnIndex, e.RowIndex].Value = int.Parse(cellValue).ToString("0000");
            }

            if (!this.btnSave.Focused)
            {
                if (this.currentWorkerCount > 0)
                {
                    if (!this.DoValidation(false))
                    {
                        return;
                    }
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBox1.SelectedIndex == 0)
            {
                this.MaxLightAddress = ConfigInfo.MaxLightAddress1;
                this.MinLightAddress = ConfigInfo.MinLightAddress1;
            }
            else if (this.comboBox1.SelectedIndex == 1)
            {
                this.MaxLightAddress = ConfigInfo.MaxLightAddress2;
                this.MinLightAddress = ConfigInfo.MinLightAddress2;
            }
            else if (this.comboBox1.SelectedIndex == 2)
            {
                this.MaxLightAddress = ConfigInfo.MaxLightAddress3;
                this.MinLightAddress = ConfigInfo.MinLightAddress3;
            }

            this.txtWorkerCount.Text = string.Empty;
            this.GetWorkersAndLightsSetup();
            this.InitWorkersNumber();
        }
    }
}
